﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;

using System.Runtime.Serialization.Json;
using Microsoft.Http;

namespace Utility
{
    public class JsonUtility
    {
        public HttpContent GetContent<T>(T t)
        {
            var strContent = ToJson(t);
            var data = Encoding.UTF8.GetBytes(strContent);
            return HttpContent.Create(data, "application/json");
        }

        public string ToJson<T>(T obj)
        {
            var ds = new DataContractJsonSerializer(typeof(T));
            using (var ms = new MemoryStream())
            {
                ds.WriteObject(ms, obj);
                var strJSON = Encoding.UTF8.GetString(ms.ToArray()); ;
                return strJSON;
            }
        }

        public T Deserialize<T>(string sJson) where T : class
        {
            var ds = new DataContractJsonSerializer(typeof(T));
            using (var ms = new MemoryStream(Encoding.UTF8.GetBytes(sJson)))
            {
                var obj = (T)ds.ReadObject(ms);
                return obj;
            }
        }
    }

}
